﻿using Enums;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using XF.Common;
using XF.ExControls;

namespace KYBM
{
    public partial class FrmSaleStatementUnclean : XFFormEx
    {
        private readonly XF.BLL.Bill_DTOItems bll = new XF.BLL.Bill_DTOItems();
        private readonly XF.BLL.Base_CheckOut bllCheckOut = new XF.BLL.Base_CheckOut();
        private readonly XF.BLL.Bill_Receipt bllReceipt = new XF.BLL.Bill_Receipt();
        private readonly XF.BLL.Base_Customer bllCustomer = new XF.BLL.Base_Customer();
        int iCustomerId = -1;
        DataTable dtUnit = GenerateData.GetUnit(false);

        List<int> lstUpdate = new List<int>();

        public FrmSaleStatementUnclean(int customerId)
        {
            InitializeComponent();
            iCustomerId = customerId;
        }

        private void FrmSaleStatement_Load(object sender, EventArgs e)
        {
            xfDataGridView1.AutoGenerateColumns = false;
            BindData();
        }

        private void BindData()
        {
            lstUpdate.Clear();
            List<XF.Model.V_SaleStatement> models = bll.ToStatementList(bll.GetSaleStatementUnclean(iCustomerId).Tables[0]);
            XF.Model.Base_CheckOut checkOut = bllCheckOut.GetLastModel(iCustomerId);
            xfDataGridView1.Rows.Clear();
            //增加上期结欠数据
            xfDataGridView1.Rows.Add();
            xfDataGridView1.Rows[0].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#00B0F0");
            xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].ReadOnly = true;
            xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[ColMateriel.Name].Value = "老欠";
            if (checkOut == null)
            {
                xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[xfDataGridView1.ColumnCount - 1].Value = 0;
                xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[ColOrderDate.Name].Value = "无";
            }
            else
            {
                xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[xfDataGridView1.ColumnCount - 1].Value = checkOut.Arrears;
                xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[ColOrderDate.Name].Value = checkOut.CheckOutDate.ToString("yyyy-MM-dd");
            }
            foreach (XF.Model.V_SaleStatement model in models)
            {
                int count = xfDataGridView1.RowCount;
                xfDataGridView1.Rows.Add();
                xfDataGridView1.Rows[count].Cells[ColId.Name].Value = model.Id;
                xfDataGridView1.Rows[count].Cells[ColRecordType.Name].Value = model.RecordType;
                xfDataGridView1.Rows[count].Cells[ColCustomerId.Name].Value = model.CustomerId;
                xfDataGridView1.Rows[count].Cells[ColOrderDate.Name].Value = model.OrderDate;
                xfDataGridView1.Rows[count].Cells[ColMateriel.Name].Value = model.Materiel;
                xfDataGridView1.Rows[count].Cells[ColQty.Name].Value = model.Qty;
                xfDataGridView1.Rows[count].Cells[ColPrice.Name].Value = model.Price;
                if(model.RecordType == 1)
                {
                    xfDataGridView1.Rows[count].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#FFA500");
                    xfDataGridView1.Rows[count].Cells[ColPaid.Name].Value = model.Paid;
                }
                else
                {
                    xfDataGridView1.Rows[count].Cells[ColUnit.Name].Value = dtUnit.Select("Value = " + zDataConverter.ToInt(model.Unit))[0]["Text"];
                    xfDataGridView1.Rows[count].Cells[ColTotlePrice.Name].Value = model.Price * model.Qty;
                    if (model.Paid == null)
                    {
                        xfDataGridView1.Rows[count].Cells[ColPaid.Name].Value = model.Price * model.Qty;
                    }
                    else
                    {
                        xfDataGridView1.Rows[count].Cells[ColPaid.Name].Value = model.Paid;
                    }
                }
            }
            ////增加汇总记录
            //xfDataGridView1.Rows.Add();
            //xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].ReadOnly = true;
            //xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[xfDataGridView1.ColumnCount - 2].Value = "合计：";
            //xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[xfDataGridView1.ColumnCount - 1].Value = GetTotle();
            //xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[xfDataGridView1.ColumnCount - 4].Value = "欠款金额："; 
            //xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[xfDataGridView1.ColumnCount - 3].Value = 0;
            //xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[xfDataGridView1.ColumnCount - 3].ReadOnly = false;
        }

        private decimal GetTotle()
        {
            decimal dTotle = zDataConverter.ToDecimal(xfDataGridView1.Rows[0].Cells[xfDataGridView1.ColumnCount - 1].Value);
            for(int i=1;i<xfDataGridView1.RowCount -1;i++)
            {
                dTotle += zDataConverter.ToDecimal(xfDataGridView1.Rows[i].Cells[ColPaid.Name].Value);
            }
            return dTotle;
        }

        private void xfDataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (!lstUpdate.Contains(e.RowIndex))
            {
                lstUpdate.Add(e.RowIndex);
            }
            if (e.ColumnIndex == ColPaid.Index)
            {
                //xfDataGridView1.Rows[xfDataGridView1.RowCount - 1].Cells[xfDataGridView1.ColumnCount - 1].Value = GetTotle();
            }
        }

        private void tsBtnSave_Click(object sender, EventArgs e)
        {
            xfDataGridView1.EndEdit();
            List<int> indexs = xfDataGridView1.GetSelectedRowsIndex();
            if (indexs.Count == 1)
            {
                decimal dTotlePrice = zDataConverter.ToInt(xfDataGridView1.Rows[0].Cells[ColPaid.Name].Value);
                decimal dTotlePaid = 0;
                DateTime dtCheckOut = new DateTime(2020, 1, 1);
                if (indexs[0] > 0)
                {
                    dtCheckOut = DateTime.Parse(xfDataGridView1.Rows[indexs[0]].Cells[ColOrderDate.Name].Value.ToString());
                }
                for (int i = 1; i < xfDataGridView1.RowCount; i++)
                {
                    int iId = zDataConverter.ToInt(xfDataGridView1.Rows[i].Cells[ColId.Name].Value); 
                    int iRecordType = zDataConverter.ToInt(xfDataGridView1.Rows[i].Cells[ColRecordType.Name].Value);
                    DateTime dtOrderDate = DateTime.Parse(xfDataGridView1.Rows[i].Cells[ColOrderDate.Name].Value.ToString());
                    decimal dPaid = zDataConverter.ToDecimal(xfDataGridView1.Rows[i].Cells[ColPaid.Name].Value);
                    bll.UpdatePaid(iId, dPaid);
                    if (dtOrderDate <= dtCheckOut)
                    {
                        if (iRecordType == 1)
                        {
                            dTotlePaid += (dPaid * -1);
                        }
                        else
                        {
                            dTotlePrice += dPaid;
                        }
                    }
                }
                FrmDialogCheckOut frmDialogCheckOut = new FrmDialogCheckOut(iCustomerId, dtCheckOut);
                frmDialogCheckOut.CheckOut.Totle = dTotlePrice;
                frmDialogCheckOut.CheckOut.Arrears = dTotlePrice - dTotlePaid;
                if (frmDialogCheckOut.ShowDialog() == DialogResult.OK)
                {
                    if (bllCheckOut.Add(frmDialogCheckOut.CheckOut) > -1)
                    {
                        QQMessageBox.Show(
                                    this,
                                    MessageText.TIP_SUCCESS_CHECKOUT,
                                    MessageText.MESSAGEBOX_CAPTION_TIP,
                                    QQMessageBoxIcon.OK,
                                    QQMessageBoxButtons.OK);
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        QQMessageBox.Show(
                                    this,
                                    MessageText.TIP_ERROR_CHECKOUT,
                                    MessageText.MESSAGEBOX_CAPTION_TIP,
                                    QQMessageBoxIcon.Information,
                                    QQMessageBoxButtons.OK);
                    }
                    BindData();
                }
            }
            else
            {
                QQMessageBox.Show(
                                this,
                                MessageText.TIP_ERROR_SELECTCOUNT_ONE,
                                MessageText.MESSAGEBOX_CAPTION_TIP,
                                QQMessageBoxIcon.Information,
                                QQMessageBoxButtons.OK);
            }
        }

        private void tsBtnAdd_Click(object sender, EventArgs e)
        {
            xfDataGridView1.EndEdit();
            FrmDTOPlace frmDTOPlace = new FrmDTOPlace(iCustomerId);
            if(frmDTOPlace.ShowDialog() == DialogResult.OK)
            {
                BindData();
            }
        }

        private void tsBtnUpdate_Click(object sender, EventArgs e)
        {
            xfDataGridView1.EndEdit();
            List<int> indexs = xfDataGridView1.GetSelectedRowsIndex();
            if (indexs.Count == 1)
            {
                int iType = zDataConverter.ToInt(xfDataGridView1.Rows[indexs[0]].Cells[ColRecordType.Name].Value);
                if (indexs[0] > 0 && iType == 0)
                {
                    foreach (int index in lstUpdate)
                    {
                        if (zDataConverter.ToInt(xfDataGridView1.Rows[index].Cells[ColRecordType.Name].Value) == 0)
                        {
                            bll.UpdatePaid(zDataConverter.ToInt(xfDataGridView1.Rows[index].Cells[ColId.Name].Value), zDataConverter.ToDecimal(xfDataGridView1.Rows[index].Cells[ColPaid.Name].Value));
                        }
                    }
                    lstUpdate.Clear();

                    int iId = zDataConverter.ToInt(xfDataGridView1.Rows[indexs[0]].Cells[ColId.Name].Value);
                    XF.Model.Bill_DTOItems item = bll.GetDetailModel(iId);
                   
                    FrmDTODetail frmDTODetail = new FrmDTODetail((int)item.DTOOrderId);
                    if (frmDTODetail.ShowDialog() == DialogResult.OK)
                    {
                        BindData();
                    }
                }
                else
                {
                    QQMessageBox.Show(
                            this,
                            MessageText.TIP_ERROR_SELECT_DTOORDER,
                            MessageText.MESSAGEBOX_CAPTION_TIP,
                            QQMessageBoxIcon.Information,
                            QQMessageBoxButtons.OK);
                }
            }
            else
            {
                QQMessageBox.Show(
                            this,
                            MessageText.TIP_ERROR_SELECTCOUNT_ONE,
                            MessageText.MESSAGEBOX_CAPTION_TIP,
                            QQMessageBoxIcon.Information,
                            QQMessageBoxButtons.OK);
            }
        }

        private void tsBtnPay_Click(object sender, EventArgs e)
        {
            xfDataGridView1.EndEdit();
            List<int> indexs = xfDataGridView1.GetSelectedRowsIndex();
            XF.Model.Bill_Receipt model = new XF.Model.Bill_Receipt();
            XF.Model.Base_Customer customer = bllCustomer.GetModel(iCustomerId);
            if (customer != null)
            {
                model.CustomerId = customer.Id;
                model.CustomerCode = customer.CustomerCode;
                model.CustomerName = customer.CustomerName;
            }
            if (indexs.Count == 1 && indexs[0] > 0)
            {
                model.PaidDate = DateTime.Parse(xfDataGridView1.Rows[indexs[0]].Cells[ColOrderDate.Name].Value.ToString());
            }
            else
            {
                model.PaidDate = DateTime.Now;
            }
            model.PaidAmount = 0;
            FrmDialogReceipt frmDialogReceipt = new FrmDialogReceipt();
            frmDialogReceipt.Receipt = model;
            if (frmDialogReceipt.ShowDialog() == DialogResult.OK)
            {
                if (bllReceipt.Add(frmDialogReceipt.Receipt) > -1)
                {
                    QQMessageBox.Show(
                                this,
                                MessageText.TIP_SUCCESS_CHECKOUT,
                                MessageText.MESSAGEBOX_CAPTION_TIP,
                                QQMessageBoxIcon.OK,
                                QQMessageBoxButtons.OK);
                }
                else
                {
                    QQMessageBox.Show(
                                this,
                                MessageText.TIP_ERROR_CHECKOUT,
                                MessageText.MESSAGEBOX_CAPTION_TIP,
                                QQMessageBoxIcon.Information,
                                QQMessageBoxButtons.OK);
                }
                BindData();
            }
        }

        private void tsBtnExport_Click(object sender, EventArgs e)
        {
            Type[] columnTypes = new Type[10];
            columnTypes[0] = typeof(int);
            columnTypes[1] = typeof(int);
            columnTypes[2] = typeof(int);
            columnTypes[3] = typeof(string);
            columnTypes[4] = typeof(string);
            columnTypes[5] = typeof(decimal);
            columnTypes[6] = typeof(string);
            columnTypes[7] = typeof(decimal);
            columnTypes[8] = typeof(decimal);
            columnTypes[9] = typeof(decimal);

            string msg = "";
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Title = "保存excel文件";
            saveFileDialog1.Filter = "excel03文件(*.xls)|*.xls|excel07文件(*.xlsx)|*.xlsx";
            saveFileDialog1.RestoreDirectory = false;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ExcelOptioner.Export(xfDataGridView1, saveFileDialog1.FileName, ref msg,false, columnTypes);
                MessageBox.Show(msg);
            }
        }
    }
}
